//
//  SecondViewController.m
//  protesteya
//
//  Created by Diego Martin Acosta Arreche on 9/14/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "ComplainsMapController.h"
#import "TwitterInvoker.h"
#import "ResponseParser.h"
#import "CustomAnnotation.h"
#import "ComplainImageFullScreenController.h"

@interface ComplainsMapController ()
@property (strong, nonatomic) IBOutlet MKMapView *mapComplains;
@property (nonatomic, strong) UIImage *selectedImage;
@end

@implementation ComplainsMapController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
    _mapComplains.delegate = self;
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
    _locationManager = nil;
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    GetTweetsListByLocationRequest *request = [[GetTweetsListByLocationRequest alloc] init];
    
    request.latitude = [NSString stringWithFormat:@"%f", _locationManager.location.coordinate.latitude];
    request.longitude = [NSString stringWithFormat:@"%f", _locationManager.location.coordinate.longitude];
    
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
    
    
    _invoker = [[TwitterInvoker alloc] init];
    _invoker.tweeterInvokerDelegate = self;
    [_invoker GetTweetsListByLocation:request];
}


-(void)getResponse:(NSDictionary *)response
{
    ResponseParser *parser = [[ResponseParser alloc] init];
    GetTweetsListResponse *getTweetListResponse = [parser ParseGetTweetsListResponse:(NSDictionary *)response];
    
    if(getTweetListResponse.responseType == TwitterResponseError)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:getTweetListResponse.errorMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    }
    else
    {
        CLLocationDistance locationRadius = [GEOCODE_RADIUS doubleValue] * 1000;
        _mapComplains.region = MKCoordinateRegionMakeWithDistance(_locationManager.location.coordinate, locationRadius, locationRadius);
        
        for(NSDictionary *tweetItem in getTweetListResponse.tweetsList)
        {
            GetTweetResponse *tweet = [parser ParseGetTweetResponse:tweetItem withImage:NO];
            
            CLLocationCoordinate2D location;
            location.latitude = [tweet.latitude doubleValue];
            location.longitude = [tweet.longitude doubleValue];
            
            CustomAnnotation *newAnnotation = [[CustomAnnotation alloc] initWithLocation:location];
            newAnnotation.title = tweet.text;
            newAnnotation.tweet = tweetItem;
            
            [_mapComplains addAnnotation:newAnnotation];
        }
        
        _locationManager = nil;
    }
    
    _invoker.tweeterInvokerDelegate = nil;
}

- (MKAnnotationView *)mapView:(MKMapView *)sender viewForAnnotation:(id<MKAnnotation>)annotation
{
    static NSString *reuseId = @"StandardPin";
    
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[sender
                                                         dequeueReusableAnnotationViewWithIdentifier:reuseId];
    if (annotationView == nil && [annotation isKindOfClass:[CustomAnnotation class]])
    {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
        annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        annotationView.canShowCallout = YES;
    }
    
    annotationView.annotation = annotation;
    
    return annotationView;   
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    if([view.annotation isKindOfClass:[CustomAnnotation class]])
    {
        [self performSegueWithIdentifier:@"complainDetailFromMap" sender:view.annotation];
    }
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    if ([view.annotation isKindOfClass:[CustomAnnotation class]])
    {
        ResponseParser *parser = [[ResponseParser alloc] init];
        NSDictionary *tweet = ((CustomAnnotation *)view.annotation).tweet;
        
        UIImage *tweetImage = [parser GetTweetImage:tweet];
        if(tweetImage)
        {
            UIImageView *imageView = [[UIImageView alloc] initWithImage:tweetImage];
            imageView.frame = CGRectMake(0,0,31,31);
            view.leftCalloutAccessoryView = imageView;
            view.leftCalloutAccessoryView.userInteractionEnabled = YES;
            _selectedImage = imageView.image;

            tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageToFullScreen)];
            tap.delegate = self;
            [view.leftCalloutAccessoryView addGestureRecognizer:tap];
        }
    }
}

-(void)imageToFullScreen{
    [self performSegueWithIdentifier:@"imageFullScreenFromMap" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([sender isKindOfClass:[CustomAnnotation class]])
    {
        NSDictionary *tweet = ((CustomAnnotation *)sender).tweet;
        [segue.destinationViewController setDetail:tweet];
    }
    else if ([[segue identifier] isEqualToString:@"imageFullScreenFromMap"])
    {
        [segue.destinationViewController setImageFullScreen:_selectedImage];
    }
}

@end
